package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDTO;
import com.heima.model.search.dto.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDTO dto) {
                log.info("保存搜索历史记录开始,文章信息{}",dto);
        if (dto.getSearchWords() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"没有搜索关键字");
        }
        //查询行为实体类
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getLoginUserId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"查询行为实体类失败");
            log.error("查询行为实体类出错");
        }
        //获取行为实体类
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有该行为实体类");
        }
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId")
                .is(behaviorEntry.getId()).and("keyword").is(dto.getSearchWords())), ApUserSearch.class);
        if (userSearch == null) {
            //为空保存关键字
            userSearch = new ApUserSearch();
            userSearch.setEntryId(behaviorEntry.getId());
            userSearch.setKeyword(dto.getSearchWords());
            userSearch.setCreatedTime(new Date());
            mongoTemplate.insert(userSearch);
            log.info("保存搜索记录成功");
            return;
        }
        //存在修改为当前时间
        userSearch.setCreatedTime(new Date());
        mongoTemplate.save(userSearch);
        log.info("更新搜索记录时间");
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        //查询行为实体类
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null?null : user.getId(), dto.getEquipmentId());
        if (! result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"查询行为实体类失败");
            log.error("查询行为实体类出错");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有该行为实体类");
        }
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(10), ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"搜素记录id不能为空");
        }
        //获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        //查询行为实体类
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null?null : user.getId(), dto.getEquipmentId());
        if (! result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"查询行为实体类失败");
            log.error("查询行为实体类出错");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有该行为实体类");
        }
        //删除搜索记录
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("_id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
